package com.wits100.demoplayer;

/**
 * Created by terry on 2017-07-25.
 */



import android.net.Uri;
import android.os.Environment;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.wits.util.ImageCache;
import com.wits.util.MD5;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by zhengboyuan on 2016-12-29.
 */

public class SimpleImageCache implements ImageCache {

    public String CACHE_PATH = "cache";

    private File cache;

    public SimpleImageCache() {

    }

    public String getCachePath() {
        File cache = new File(Environment.getExternalStorageDirectory(), CACHE_PATH);
        return cache.getPath();
    }


    @Override
    public boolean open(String cachePath) {
        boolean found = false;
        cache = new File(cachePath);
        if (cache.exists()) {
            found = true;
        } else {
            found = cache.mkdirs();
        }
        return found;
    }

    @Override
    public void close() {

    }

    @Override
    public void clear() {

    }

    @Override
    public List<String> getCached() {
        return null;
    }

    @Override
    public void getImage(String uri, OnImageReady handler) {
        String name = MD5.getMD5(uri) + uri.substring(uri.lastIndexOf("."));
        File file = new File(cache, name);
        if (file.exists()) {
            Uri imageUri = Uri.fromFile(file);
            handler.handle(uri, imageUri);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.get(uri, null, new ImageResponseHandler(file, uri, handler));
        }
    }

    class ImageResponseHandler extends AsyncHttpResponseHandler {

        File file;
        String uri;
        OnImageReady handler;

        public ImageResponseHandler(File file, String uri, OnImageReady handler) {
            this.file = file;
            this.uri = uri;
            this.handler = handler;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(responseBody);

                Uri imageUri = Uri.fromFile(file);
                this.handler.handle(uri, imageUri);
            } catch (Throwable t) {
                this.handler.handle(uri, null);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            this.handler.handle(uri, null);
        }
    }


}
